<!--
author:        hejiyang <silentmanager@163.com>
date:          2024-11-13 18:12:38
component:     allocation
Copyright © YourCompanyName All rights reserved
分配客户
-->
<template>
  <el-dialog v-model="isVisible" title="分配客户" width="500px" @update:visible="handleClose">
    <div style="display: flex; align-items: center; justify-content: center">
      <el-form ref="formRef" :rules="rules" label-position="left" :model="form">
        <el-form-item prop="deptId" label="部门">
          <el-select v-model="form.deptId" placeholder="请选择部门" style="width: 300px">
            <el-option
              v-for="item in deptList"
              :key="item.id"
              :value="item.id"
              :label="item.name" /></el-select
        ></el-form-item>
        <el-form-item prop="roleId" label="角色">
          <el-select
            :options="roleList"
            v-model="form.roleId"
            placeholder="请选择角色"
            style="width: 300px"
          >
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :value="item.id"
              :label="item.nickname" /></el-select
        ></el-form-item>
      </el-form>
    </div>

    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
      <el-button type="primary" :loading="loading" @click="handleSave">分配</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import {
  distributeCustomer,
  simpleListDept,
  SimpleListDeptRes,
  simpleListUser,
  SimpleListUserRes
} from '@/api/customer'
import { ElForm } from 'element-plus'
import { ref, defineExpose } from 'vue'
import { reactive } from 'vue'

interface Props {
  selectId: number[]
}
const emit = defineEmits<{
  (e: 'success'): void // 添加 success 事件
}>()
const props = defineProps<Props>()
const message = useMessage()

// ----------------------------- 表单 -----------------------------
const loading = ref(false)
const formRef = ref<InstanceType<typeof ElForm> | null>(null)
const form = ref({
  deptId: undefined,
  roleId: undefined
})
const rules = reactive({
  deptId: [{ required: true, message: '请选择部门', trigger: 'change' }],
  roleId: [{ required: true, message: '请选择角色', trigger: 'change' }]
})
// 部门角色options
const deptList = ref<SimpleListDeptRes[]>([])
const roleList = ref<SimpleListUserRes[]>([])

// 获取部门角色options
const simpleListDeptFn = async () => {
  try {
    const res = await simpleListDept()
    deptList.value = res
  } catch (e) {
    console.error(e)
  }
}
const simpleListUserFn = async () => {
  try {
    const res = await simpleListUser(form.value.deptId || '')
    roleList.value = res
  } catch (e) {
    console.error(e)
  }
}
// 提交
const handleSave = async () => {
  loading.value = true
  try {
    await formRef?.value?.validate()
    const res = await distributeCustomer({
      ids: props.selectId,
      ownerUserId: form.value.roleId || ''
    })
    if (res.code === 0) {
      message.success('分配成功')
      handleClose()
      emit('success')
    }
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}
// 监听部门的值请求角色option
watch(
  () => form.value.deptId, // 监听 deptId
  async (newValue) => {
    if (newValue === undefined) {
      // 如果新值是 undefined，不触发请求
      roleList.value = []
      return
    }
    await simpleListUserFn() // 正确调用函数
  }
)
onMounted(() => {
  simpleListDeptFn()
})
// ----------------------------- 弹窗状态 -----------------------------
const isVisible = ref(false)
// 暴露控制弹窗的方法
defineExpose({
  open() {
    isVisible.value = true
  },
  close() {
    isVisible.value = false
  }
})
const handleClose = () => {
  isVisible.value = false
  form.value = {
    deptId: undefined,
    roleId: undefined
  }
}
</script>
